package com.example.teach.config;


import com.example.teach.config.interceptor.JwtAuthFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
/**
 * Spring Security
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    // 注入JWT过滤器（推荐通过@Bean注入，而非直接new）
    @Bean
    public JwtAuthFilter jwtAuthFilter() {
        return new JwtAuthFilter();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // 允许跨域（前后端分离项目必备）
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                // 关闭CSRF（前后端分离项目常用）
                .csrf(csrf -> csrf.disable())
                // 配置请求权限
                .authorizeHttpRequests(auth -> auth
                        // 明确指定请求方法和路径，避免模糊匹配问题
                        .requestMatchers("/user/login", "/user/register","/ai/chat").permitAll()
                        // 允许所有OPTIONS请求（预检请求）
                        .requestMatchers(request -> "OPTIONS".equals(request.getMethod())).permitAll()
                        // 其他请求需要认证
                        .anyRequest().authenticated()
                )
                // 添加JWT过滤器
                .addFilterBefore(jwtAuthFilter(), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    // 配置跨域（解决前端请求跨域问题）
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList("http://localhost:5173")); // 替换为前端实际域名
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"));
        config.setAllowedHeaders(Arrays.asList("*"));
        config.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
    /*@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())  // 替代旧的.csrf().disable()
                .authorizeHttpRequests(auth -> auth  // 使用authorizeHttpRequests替代authorizeRequests
                        .requestMatchers("/login").permitAll()  // 允许匿名访问登录接口
                        .requestMatchers("/register").permitAll()  // 允许匿名访问注册接口
                        .anyRequest().authenticated()  // 其他所有请求需要认证
                )
                // 将JWT过滤器添加到过滤器链中，在用户名密码认证过滤器之前执行
                .addFilterBefore(new JwtAuthFilter(), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }*/
}
